package com.wenjh.jdmzt.android.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.DataSetObserver;
import android.os.Build;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.HeaderViewListAdapter;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.wenjh.jdmzt.AndroidKit;
import com.wenjh.jdmzt.util.Log4Android;

@SuppressLint("NewApi")
public class HandyListView extends ListView {
	public interface OnSizeChangedListener {
		public void onSizeChanged(HandyListView listView, int w, int h, int oldw, int oldh);
	}
	
	private View addOfEmptyListView = null;
	private View mEmptyListView = null;
	private View mLoadingListView = null;
	private OnSizeChangedListener mSizeListener = null;
	private int mFadingEdgeColor = -1;
	private int mListViewHiddenValue = View.GONE;
	
	private boolean scrolling = false;
	private boolean scorllEndReflush = true;
	
	//private Log4Android log = new Log4Android("HandyListView");
	private ListAdapter listAdapter = null;
	private OnScrollListener onScrollListener = null;
	private OnItemLongClickListener itemLongClickListener = null;
	private DataLoadPolicy loadPolicy = DataLoadPolicy.Idle;
	
	
	public static enum DataLoadPolicy {
		// 任何时候都加载
		Anytime, 
		// 空闲的时候加载，对于listview就是滑动结束的时候
		Idle, 
		// 对于一些简单的，不是很耗性能的操作可以加载
		Easy
	}
	
	public HandyListView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initHandyListView();
	}

	public HandyListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initHandyListView();
	}

	public HandyListView(Context context) {
		super(context);
		initHandyListView();
	}
	
	/**
	 * 设置当List滑动结束时，是否刷新界面
	 * @param scorllEndReflush true表示开启特性，false关闭
	 */
	public void setScorllEndReflush(boolean scorllEndReflush) {
		this.scorllEndReflush = scorllEndReflush;
	}
	
	public boolean isScorllEndReflush() {
		return scorllEndReflush;
	}
	
	public void setLoadPolicy(DataLoadPolicy loadPolicy) {
		this.loadPolicy = loadPolicy;
	}
	
	public DataLoadPolicy getLoadPolicy() {
		return loadPolicy;
	}
	
	/**
	 * 是否正在拖动
	 * @return
	 */
	public boolean isScrolling() {
		return scrolling;
	}
	
	public void setScrolling(boolean scrolling) {
		this.scrolling = scrolling;
	}
	
	@Override
	public void setOnScrollListener(OnScrollListener l) {
		this.onScrollListener = l;
	}
	
	@Override
	public void addFooterView(View v) {
		super.addFooterView(v);
	}
	
	private void initHandyListView() {
		super.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if(onScrollListener != null) {
					onScrollListener.onScrollStateChanged(view, scrollState);
				}
				switch (scrollState) {
		        case OnScrollListener.SCROLL_STATE_IDLE:
		        	scrolling = false;
		        	
		        	if(isScorllEndReflush() && listAdapter != null  && listAdapter instanceof BaseAdapter) {
		        		((BaseAdapter)listAdapter).notifyDataSetChanged();
		        	}
		            break;
		            
		        case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
		        	scrolling = true;
		            break;
		            
		        case OnScrollListener.SCROLL_STATE_FLING:
		        	scrolling = true;
		            break;
		        }
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if(onScrollListener != null) {
					onScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
				}
			}
		});
	}
	
	
	
	/**
	 * 滚动到列表顶部
	 */
	public void scrollToTop() {
		/*
		 * 数据为空
		 */
		if(getAdapter() == null || getAdapter().getCount() < 1 ){
			return;
		}
		
		/*
		 * 2.2版本以下不支持向上滚动的 API
		 */
		if(Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
			setSelection(0);
			return;
		}
		
		
		/*
		 * 自动滚动到列表顶部
		 */
		
		/*
		 * 至少从第10项位置开始滚动
		 */
		if(getFirstVisiblePosition() > 5) {
			setSelection(5);
		}
		
		if(AndroidKit.isIcsVsersion()) { // 4.0的API
			smoothScrollToPositionFromTop(0, 0);
		} else {
			smoothScrollToPosition(0);
		}
	}
	
	/**
	 * accepts View.INVISIBLE or View.GONE, default is View.GONE
	 * might not work with empty view
	 * @param hiddenValue
	 */
	public void setListViewHiddenValue(int hiddenValue) {
		mListViewHiddenValue = hiddenValue;
	}

	/**
	 * 多选模式下 (通过 {@link #setMultipleSelector(MultipleSelector)} 方法设置了多选器），Adapter必须是 {@link MultipleSelectionAdapter} 的子类.
	 * 否则将发生异常。
	 */
	@Override
	public void setAdapter(ListAdapter adapter) {
		if (mLoadingListView != null)
			mLoadingListView.setVisibility(View.GONE);
		
		setVisibility(View.VISIBLE);
		super.setEmptyView(mEmptyListView);
		mEmptyListView = null;
		super.setAdapter(adapter);
		onAdapterDataChanged(adapter == null || adapter.isEmpty());
		
		if(adapter != null) {
			adapter.registerDataSetObserver(new DataSetObserver() {
				@Override
				public void onChanged() {
					onAdapterDataChanged(listAdapter.isEmpty());
				}
			});
		}
		
		this.listAdapter = adapter;
	}
	
	protected void onAdapterDataChanged(boolean empty) {
		if(addOfEmptyListView != null) {
			if(empty && isShowEmptyView()) {
				addOfEmptyListView.setVisibility(View.VISIBLE);
			} else {
				addOfEmptyListView.setVisibility(View.GONE);
			}
		}
	}
	
	protected boolean isShowEmptyView() {
		return true;
	}
	
	@Override
	public View getEmptyView() {
		if (mEmptyListView != null)
			return mEmptyListView;
		return super.getEmptyView();
	}

	@Override
	public void setEmptyView(View emptyView) {
		mEmptyListView = emptyView;
		if (mEmptyListView != null)
			mEmptyListView.setVisibility(View.GONE);
	}
	
	public void addEmptyView(View emptyView) {
		addOfEmptyListView = emptyView;
		if(addOfEmptyListView != null) {
			addOfEmptyListView.setVisibility(View.GONE);
			
			LinearLayout linearLayout = new LinearLayout(getContext());
			linearLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
			linearLayout.setGravity(Gravity.CENTER);
			linearLayout.addView(addOfEmptyListView);
			linearLayout.setBackgroundDrawable(emptyView.getBackground());
			
			addHeaderView(linearLayout);
		}
	}
	
	public void setEmptyViewVisible(boolean isVisible){
		if(addOfEmptyListView != null){
			addOfEmptyListView.setVisibility(isVisible ? View.VISIBLE : View.GONE);
		}
	}
	
	public void setLoadingListView(View loadingView) {
		mLoadingListView = loadingView;
		if (mLoadingListView != null) {
			setVisibility(mListViewHiddenValue);
			mLoadingListView.setVisibility(View.VISIBLE);
		}
	}
	
	public void setOnSizeChangedListener(OnSizeChangedListener listener) {
		mSizeListener = listener;
	}
	
	@Override
	public void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);
		if (mSizeListener != null)
			mSizeListener.onSizeChanged(this, w, h, oldw, oldh);
	}
	
	public ListAdapter getBaseAdapter() {
		ListAdapter adapter = super.getAdapter();
		if (adapter instanceof HeaderViewListAdapter) 
			return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
		return adapter;
	}

	public void setFadingEdgeColor(int color) {
		mFadingEdgeColor = color;
	}
	
	@Override
	public void setOnItemLongClickListener(
			android.widget.AdapterView.OnItemLongClickListener listener) {
		this.itemLongClickListener = listener;
		
		super.setOnItemLongClickListener(new ItemLongclickListenerWrapper(itemLongClickListener));
	}
	
	public OnItemLongClickListener getOnItemLongClickListenerInWrapper() {
		return this.itemLongClickListener;
	}
	
	public final class ItemLongclickListenerWrapper implements android.widget.AdapterView.OnItemLongClickListener {
		
		private android.widget.AdapterView.OnItemLongClickListener listener = null;
		
		public ItemLongclickListenerWrapper(android.widget.AdapterView.OnItemLongClickListener listener) {
			this.listener = listener;
		}
		
		public android.widget.AdapterView.OnItemLongClickListener getWapperListener() {
			return listener;
		}
		
		@Override
		public boolean onItemLongClick(AdapterView<?> parent, View view,
				int position, long id) {
			/*
			 * 如果有headerView的话，position要减去hedaerView的个数
			 */
			
			if(listener != null) {
				return listener.onItemLongClick(parent, view, position - getHeaderViewsCount(), id);
			}
			return false;
		}
	}
	
	private boolean interceptItemClick = false;
	/**
	 * 设置拦截所有Item点击事件
	 * @param interceptItemClick
	 */
	public void setInterceptItemClick(boolean interceptItemClick) {
		this.interceptItemClick = interceptItemClick;
	}
	
	/**
	 * 是否已拦截Item点击事件
	 * @return
	 */
	public boolean isInterceptItemClick() {
		return interceptItemClick;
	}
	
	public boolean performItemClick(View view, int position, long id) {
		/*
		 * add了headerview之后，点击的position要减去headerView的个数.
		 */
		int topOffset = getHeaderViewsCount();
		
		position -= topOffset;
		
		if(interceptItemClick || getAdapter() == null || position < 0 || position >= getAdapter().getCount()) {
			return true;
		}
		
		return super.performItemClick(view, position, id);
    }
	
	@Override
	public int getSolidColor() {
		if (mFadingEdgeColor == -1)
			return super.getSolidColor();
		return mFadingEdgeColor;
	}
	
	public interface OnInterceptTouchListener {
		boolean onInterceptTouchEvent(MotionEvent ev);
	}
	
	private OnInterceptTouchListener interceptTouchListener = null;
	public void setOnInterceptTouchListener(OnInterceptTouchListener listener) {
		this.interceptTouchListener = listener;
	}
	
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		if(interceptTouchListener != null) {
			return interceptTouchListener.onInterceptTouchEvent(ev);
		}
		return super.onInterceptTouchEvent(ev);
	}
	
}
